package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"zg2zy1/models/mysql"
	"zg2zy1/models/redis"
	"zg2zy1/zg2zy1rpc/internal/svc"
	"zg2zy1/zg2zy1rpc/zg2zy1rpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zg2zy1rpc.LoginRequest) (*zg2zy1rpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User
	mysql.DB.Debug().Model(&user).Where("tel  =  ?", in.Tel).Find(&user)

	tel := user.Tel
	if tel == "" {

		get := redis.Client.Get("sendSms" + in.Tel + "register")
		if get.Val() != in.SendSms {
			return nil, fmt.Errorf("短信未验证")
		}
		register := mysql.User{
			Model:    gorm.Model{},
			Tel:      in.Tel,
			Password: in.Password,
		}

		err := mysql.DB.Debug().Model(&register).Create(&register).Error
		if err != nil {
			return nil, fmt.Errorf("文件创建失败")
		}
		mysql.DB.Debug().Model(&register).Where("tel = ?", in.Tel).Find(&register)
	} else {
		var login mysql.User
		mysql.DB.Debug().Model(&user).Where("tel  =  ?", in.Tel).Find(&user)

		if login.ID != 0 {
			return nil, fmt.Errorf("账户不存在")
		}

		if user.Password != in.Password {
			return nil, fmt.Errorf("密码不正确,请重新输入")
		}
		get := redis.Client.Get("sendSms" + in.Tel + "login")
		if get.Val() != in.SendSms {
			return nil, fmt.Errorf("短信未验证")
		}
	}
	return &zg2zy1rpc.LoginResponse{Id: int64(user.ID)}, nil
}
